from rest_framework import serializers
from .models import Category, Book


# class CategorySerializer(serializers.ModelSerializer):
# 	"""
# 	模型序列化类： 可以针对模型中指定字段选择
# 	"""
# 	# id = serializers.HyperlinkedIdentityField(view_name="category-detail")
# 	class Meta:
# 		model = Category
# 		# fields = "__all__"
# 		fields = ["title", "id"]


class CategorySerializer(serializers.Serializer):
    """
	自定义序列化类： 灵活，定制化
	"""
    id = serializers.PrimaryKeyRelatedField(read_only=True)
    title = serializers.CharField(max_length=30)

    # 获取列表，获取详情的get， 删除详情的delete    不需要重写任何方法
    def create(self, validated_data):
        """
		用于post
		"""
        c = Category()
        c.title = validated_data.get("title")
        c.save()
        return c

    def update(self, instance, validated_data):
        """
		用于put
		"""
        # 使用表单中的title更新实例中的title  如果表单没有传递title则使用默认实例的title
        instance.title = validated_data.get("title", instance.title)
        instance.save()
        return instance


class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ["id", "title", "category"]
